package com.example.aspect.achieve;

import com.example.aspect.annotation.ChineseCheck;
import com.example.exception.ServiceException;
import com.example.pojo.entity.Admin;
import com.example.pojo.entity.User;
import com.example.utils.JsonUtil;
import com.example.utils.ResultCodeUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Component
public class ChineseAspect {
 
    @Around("@annotation(check)")
    public Object validateUsernamePassword(ProceedingJoinPoint joinPoint, ChineseCheck check) throws Throwable {
        // 获取方法参数
        Class<?> clazz = check.value();
        Object[] args = joinPoint.getArgs();
        String regex = "[a-zA-Z0-9!@#$%^&*(),.?\":{}|<>]+";

        for (Object arg : args) {
            if (arg instanceof Map) {
                String stringify = JsonUtil.stringify(arg);
                Object parse =  JsonUtil.parse(stringify, clazz);

                if(parse instanceof Admin){
                    Admin admin = (Admin) parse;
                    // 判断是否符合字符数字规则
                    if (!admin.getUserName().matches(regex)) {
                        throw new ServiceException(ResultCodeUtil.PARAMS_ERROR);
                    }
                    if (!admin.getPassword().matches(regex)) {
                        throw new ServiceException(ResultCodeUtil.PARAMS_ERROR);
                    }
                }
                if(parse instanceof User){
                    User user = (User) parse;
                    if (!user.getUserName().matches(regex)) {
                        throw new ServiceException(ResultCodeUtil.PARAMS_ERROR);
                    }
                    if (!user.getPassword().matches(regex)) {
                        throw new ServiceException(ResultCodeUtil.PARAMS_ERROR);
                    }
                }

            }
        }
        // 继续执行方法
        return joinPoint.proceed();
    }
}